const express = require('express');

const app = express();

const fs = require("fs");

const puppeteer = require('puppeteer');

const browserUrl = fs.readFileSync("chrome.txt", "utf8");

app.get('*', function(req, res) {

    let domain = req.headers['referer'].match(/^(\w+:\/\/)?([^\/]+)/i);
    
    if (domain && domain.length >= 1) {
        domain = domain[0]
    }

    var url = domain + req.originalUrl;

    var ua = req.headers['user-agent'];

    (async () => {

        const browser = await puppeteer.connect({ browserWSEndpoint: browserUrl });

        const page = await browser.newPage(); //创建一个页面.

        page.setViewport({
            width: 1280,
            height: 1920
        })

        try {

            await page.goto(url); //到指定页面的网址.

            await page.waitFor(1500);

        } catch (err) {

            await page.close();

            await browser.disconnect();

            console.log('出现错误：' + err); // 这里捕捉到错误 `error`

        }

        res.send(await page.content());

        await page.close();

        await browser.disconnect();

    })();

});

var server = app.listen(3000, '127.0.0.1', function() {

    var host = server.address().address;

    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);

});